package com.atguigu.juc.interview.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author leimingchao
 * @create 2021-04-21 23:19
 */

class Phone implements Runnable{
    public synchronized void sendSMS(){
        System.out.println(Thread.currentThread().getId()+"\t invoke sendSMS()");
        sendEmail();
    }

    public synchronized void sendEmail(){
        System.out.println(Thread.currentThread().getId()+"\t invoke sendEmail()");
    }

    Lock lock=new ReentrantLock();
    @Override
    public void run() {
        get();
    }
    public void get(){
        // lock.lock();
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t invoke get()");
            set();
        }finally {
            //lock.unlock();
            lock.unlock();
        }
    }

    public void set(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t invoke set()");
        }finally {
            lock.unlock();
        }
    }
}

public class ReenterLockTest {
    public static void main(String[] args) {
        Phone phone=new Phone();
        new Thread(()->{
            phone.sendSMS();
        },"t1").start();

        new Thread(()->{
            phone.sendSMS();
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
            Thread t3=new Thread(phone,"t3");
            Thread t4=new Thread(phone,"t4");
            t3.start();
            t4.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
